package org.balthie.demo.jdk.util.concurrent.locks.reenterlock;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {
	private final Lock lock = new ReentrantLock();
	private final Condition condition = lock.newCondition();
	private Queue<String> queue = new LinkedList<>();
	
//	await()会释放当前锁，进入等待状态；
//
//	signal()会唤醒某个等待线程；
//
//	signalAll()会唤醒所有等待线程；
//
//	唤醒线程从await()返回后需要重新获得锁。

	public void addTask(String s) {
		lock.lock();
		try {
			queue.add(s);
			System.out.println(String.format("[%s] signalAll taskQueue size[%s]", Thread.currentThread(), queue.size()));
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}

	public String getTask() {
		lock.lock();
		try {
			while (queue.isEmpty()) {
				System.out.println(String.format("[%s] await", Thread.currentThread()));
				condition.await();
			}
			String task = queue.remove();
			System.out.println(String.format("[%s] getTask [%s]", Thread.currentThread(), task));
			return task;
		} catch (InterruptedException e) {
			System.out.println(String.format("[%s] interrupted", Thread.currentThread()));
//			被唤醒后，必须重新获取锁
			return getTask();
		} finally {
			lock.unlock();
		}
	}
}
